<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词配对游戏</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell;
            background: #f5f5f7;
            margin: 0;
            padding: 2rem;
            min-height: 100vh;
            box-sizing: border-box;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0.1rem;
            display: flex;
        }

        .column {
            width: 50%;
            display: flex;
            flex-wrap: wrap;
            gap: 0.25rem;
            justify-content: center;
        }

        .word-card {
            background: white;
            border-radius: 15px;
            padding: 0.5rem;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            min-width: min-content;
            margin: 0.25rem;
            flex: 0 1 auto;
            border: 2px solid transparent;
        }

        .word-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            border-color: #0071e3;
            background: linear-gradient(to bottom right, #ffffff, #f8f9fa);
        }

        .word-card.selected {
            background: linear-gradient(135deg, #0071e3, #00a3ff);
            color: white;
            border-color: #005bb8;
        }

        .word-card.correct {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            border-color: #388e3c;
        }

        .word-card.wrong {
            animation: shake 0.5s;
            background: linear-gradient(135deg, #ff4444, #ff6b6b);
            color: white;
            border-color: #d32f2f;
        }

        .score-board {
            text-align: center;
            margin-bottom: 2rem;
            font-size: 1.5rem;
        }

        .score {
            display: inline-block;
            margin: 0 1rem;
            padding: 0.5rem 1rem;
            border-radius: 10px;
            background: white;
        }

        .correct-score {
            color: #4CAF50;
        }

        .wrong-score {
            color: #ff4444;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(10px); }
            75% { transform: translateX(-10px); }
        }

        @media (max-width: 768px) {
            .container {
                grid-template-columns: 1fr;
            }
        }

        .divider {
            width: 2px;
            background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.1));
            margin: 0 1rem;
        }
    </style>
</head>
<body>
    <div class="score-board">
        <div class="score correct-score">正确：<span id="correctCount">0</span></div>
        <div class="score wrong-score">错误：<span id="wrongCount">0</span></div>
        <div style="margin-top: 1rem;">
            <input type="file" id="fileInput" accept=".xlsx" style="display: none;">
            <button onclick="document.getElementById('fileInput').click()" style="padding: 0.5rem 1rem; background: #0071e3; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem;">导入Excel</button>
        </div>
    </div>

    <div class="container">
        <div class="column" id="englishColumn"></div>
        <div class="divider"></div>
        <div class="column" id="chineseColumn"></div>
    </div>

    <audio id="correctSound" src="success.wav"></audio>
    <audio id="wrongSound" src="error.wav"></audio>
    <audio id="victorySound" src="game-fanfare.mp3"></audio>
    <script src="xlsx.full.min.js"></script>

    <script>
        const gradients = [
            { start: '#FF6B6B', end: '#FFE66D' },
            { start: '#4ECDC4', end: '#556270' },
            { start: '#A8E6CF', end: '#DCEDC1' },
            { start: '#FFD93D', end: '#FF8E72' },
            { start: '#95E1D3', end: '#EAFFD0' },
            { start: '#6C5B7B', end: '#C06C84' },
            { start: '#00B4DB', end: '#0083B0' },
            { start: '#F7971E', end: '#FFD200' },
            { start: '#56CCF2', end: '#2F80ED' },
            { start: '#F2994A', end: '#F2C94C' }
        ];

        var words = [
            { en: "hello", zh: "你好" },
            { en: "apple", zh: "苹果" },
            { en: "dog", zh: "狗" },
            { en: "book", zh: "书" },
            { en: "car", zh: "车" },
            { en: "cat", zh: "猫" },
            { en: "computer", zh: "电脑" },
            { en: "phone", zh: "电话" },
            { en: "table", zh: "桌子" },
            { en: "chair", zh: "椅子" }
        ];

        let selectedEnglish = null;
        let selectedChinese = null;
        let correctCount = 0;
        let wrongCount = 0;
        let remainingWords = [...words];

        function shuffleArray(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
            return array;
        }

        function createWordCard(text, isEnglish, index) {
            const card = document.createElement('div');
            card.className = 'word-card';
            card.textContent = text;
            
            // 设置渐变背景
            const gradient = gradients[index % gradients.length];
            card.style.background = `linear-gradient(135deg, ${gradient.start}, ${gradient.end})`;
            card.style.color = 'white';
            card.style.textShadow = '1px 1px 2px rgba(0, 0, 0, 0.2)';
            
            card.onclick = () => selectCard(card, text, isEnglish);
            return card;
        }

        async function playWordAudio(word) {
            try {
                const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
                const data = await response.json();
                
                if (data && data[0]) {
                    // 播放发音
                    if (data[0].phonetics && data[0].phonetics.length > 0) {
                        const audioUrl = data[0].phonetics.find(p => p.audio)?.audio;
                        if (audioUrl) {
                            const audio = new Audio(audioUrl);
                            audio.play();
                        }
                    }
                }
            } catch (error) {
                console.error('Error fetching audio:', error);
            }
        }

        function selectCard(card, text, isEnglish) {
            if (card.classList.contains('correct')) return;

            if (isEnglish) {
                if (selectedEnglish) {
                    selectedEnglish.classList.remove('selected');
                }
                selectedEnglish = card;
                // 播放英文单词发音
                playWordAudio(text);
            } else {
                if (selectedChinese) {
                    selectedChinese.classList.remove('selected');
                }
                selectedChinese = card;
            }

            card.classList.add('selected');

            if (selectedEnglish && selectedChinese) {
                checkMatch();
            }
        }

        function checkMatch() {
            const englishText = selectedEnglish.textContent;
            const chineseText = selectedChinese.textContent;
            const isCorrect = words.some(word => word.en === englishText && word.zh === chineseText);

            if (isCorrect) {
                document.getElementById('correctSound').play();
                selectedEnglish.remove();
                selectedChinese.remove();
                correctCount++;
                remainingWords = remainingWords.filter(word => word.en !== englishText);
                selectedEnglish = null;
                    selectedChinese = null;

                if (remainingWords.length === 0) {
                    document.getElementById('victorySound').play();
                    setTimeout(() => {
                        alert(`🎉 胜利！\n正确: ${correctCount}次  错误: ${wrongCount}次`);
                        resetGame();
                    }, 500);
                }
            } else {
                document.getElementById('wrongSound').play();
                selectedEnglish.classList.add('wrong');
                selectedChinese.classList.add('wrong');
                wrongCount++;
                setTimeout(() => {
                    selectedEnglish.classList.remove('selected', 'wrong');
                    selectedChinese.classList.remove('selected', 'wrong');
                    selectedEnglish = null;
                    selectedChinese = null;
                }, 1000);
            }

            document.getElementById('correctCount').textContent = correctCount;
            document.getElementById('wrongCount').textContent = wrongCount;
        }

        function resetGame() {
            remainingWords = [...words];
            correctCount = 0;
            wrongCount = 0;
            document.getElementById('correctCount').textContent = '0';
            document.getElementById('wrongCount').textContent = '0';
            initGame();
        }

        function initGame() {
            const englishWords = shuffleArray([...remainingWords]);
            const chineseWords = shuffleArray([...remainingWords]);

            const englishColumn = document.getElementById('englishColumn');
            const chineseColumn = document.getElementById('chineseColumn');

            englishColumn.innerHTML = '';
            chineseColumn.innerHTML = '';

            englishWords.forEach((word, index) => {
                englishColumn.appendChild(createWordCard(word.en, true, index));
            });

            chineseWords.forEach((word, index) => {
                chineseColumn.appendChild(createWordCard(word.zh, false, index));
            });
        }

        document.getElementById('fileInput').addEventListener('change', async e => {
            const file = e.target.files[0];
            if (!file) return;

            try {
                const data = await file.arrayBuffer();
                const workbook = XLSX.read(data);
                const jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);

                if (!jsonData[0]?.中文 || !jsonData[0]?.英文) {
                    alert('文件格式错误');
                    return;
                }
                console.log(jsonData);

                const newWords = jsonData
                    .map(item => ({
                        zh: item.中文.trim(),
                        en: item.英文.trim().toLowerCase()
                    }))
                    .filter((item, index, self) =>
                        index === self.findIndex(t => t.zh === item.zh && t.en === item.en)
                    );

                words = [...newWords];
                remainingWords = [...newWords];
                alert(`导入成功 ${newWords.length} 个单词`);
                initGame();
            } catch (error) {
                alert('文件读取失败: ' + error.message);
            }
        });

        initGame();
    </script>
</body>
</html>